<template>
  <el-input :value="value" @input="valueInput" ref="scanInput" v-on:keyup.native="keyInput" v-bind="$attrs"
    :placeholder="$t('tip_please_input')">
    <template v-slot:prepend>

      <slot name="prepend">

      </slot>
    </template>

  </el-input>
</template>
<script>


export default {
  inject: ['tabActivatedInject'],
  props: {
    value: null,
  },
  data() {
    return {
      intersectionVisible: true,
    }
  },
  mounted() {
    if (typeof (IntersectionObserver) === 'function' && /native code/.test(IntersectionObserver.toString())) {
      new IntersectionObserver(([change]) => {
        // console.log(change, change.isVisible) // 被覆盖就是false，反之true
        this.intersectionVisible = change.isVisible
      }, {
        threshold: [1.0],
        delay: 100,
        trackVisibility: true,
      }).observe(this.$refs.scanInput.$el);
    }
    this.$ScanConsume.addScanConsume(this)
  },
  destroyed() {
    this.$ScanConsume.removeScanConsume(this)
  },
  computed: {
    tabActivated() {
      return this.tabActivatedInject()
    },
  },

  methods: {
    scanValue(newVal) {
      if (this.tabActivated && this.intersectionVisible) {
        this.$emit('input', newVal)
        this.$emit('enterInput', newVal)

        //处理非焦点输入元素的问题，同步移除扫码枪输入数据
        const currentFocus = document.activeElement
        if (currentFocus) {
          const input = this.$refs.scanInput.$el.querySelector("input")
          if (input != currentFocus) {
            // console.log(currentFocus, currentFocus.value, currentFocus.__vue__)
            if (currentFocus.value && _.endsWith(currentFocus.value, newVal)) {
              currentFocus.value = currentFocus.value.slice(0, currentFocus.value.length - newVal.length)
              const _vue = currentFocus.__vue__ || currentFocus.parentElement.__vue__
              if (_vue && _vue.$vnode.componentOptions && ["el-input"].includes(_vue.$vnode.componentOptions.tag)) {
                _vue.$emit("input", currentFocus.value)
                _vue.$emit("change", currentFocus.value)
              }
            }
          }
        }
        this.$nextTick(() => {
          this.$refs.scanInput.focus()
          this.$refs.scanInput.select(this.value)
        })
        return true
      }
      return false
    },
    valueInput(e) {
      this.$emit('input', e ? e.trim() : e)
    },

    keyInput(e) {
      if (e.code == "Enter" || e.key == "Enter") {

        // if (this.intersectionVisible) {
        //   this.$emit('enterInput', this.value)
        //   this.$nextTick(() => {
        //     this.$refs.scanInput.focus()
        //     this.$refs.scanInput.select(this.value)
        //   })
        // }
        this.$emit('enterInput', this.value)
        this.$nextTick(() => {
          this.$refs.scanInput.focus()
          this.$refs.scanInput.select(this.value)
        })
        e.stopPropagation();
      }
    },

  }
}

</script>
